//
//  UserAccountViewModel.swift
//  SinaWeibo
//
//  Created by 张洪毓 on 15/11/10.
//  Copyright © 2015年 张洪毓. All rights reserved.
//

import UIKit
import AFNetworking
class UserAccountViewModel: NSObject {
    
    // 增加 UserAccount 属性
    var account: UserAccount?
    var userLogin: Bool {
        return account?.access_token != nil
    }
    var token: String? {
        return account?.access_token
    }
    
    var userName: String? {
        return account?.name
    }
    
    var headIconUrl: NSURL? {
        return NSURL(string: (account?.avatar_large) ?? "")
    }
    
    
    
    //在 init 方法中获取用户账户
    override init() {
        account = UserAccount.loadAccount()
    }
    
    func loadAccessToken(code: String,finished: (error: NSError?) -> ()) {
        

        let urlString = "oauth2/access_token"
        let parameters = ["client_id": client_id,"client_secret": client_secret,"grant_type": "authorization_code","code": code,"redirect_uri": redirect_uri]
        
//        let AF = AFHTTPSessionManager()
//        AF.responseSerializer.acceptableContentTypes?.insert("text/plain")
////             AF.responseSerializer = AFHTTPResponseSerializer()
//        AF.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
//
////            // 调试服务端返回的数据
////            let str = NSString(data: result as! NSData, encoding: NSUTF8StringEncoding)
////            print(str)
//
//            if let dict = result as? [String: AnyObject] {
//
////                print(dict)
//// ["access_token": 2.00Jh9L6Bi3JmREba218f4addedmW7E, "remind_in": 107147, "uid": 1288273147, "expires_in": 107147]
//                let account = UserAccount(dict: dict)
//                //                print("account:\(account)")
//                self.loadUserInfo(account, finished: finished)
//                //                let access_token = dict["access_token"] as? String
//                //                let uid = dict["uid"] as? String
//                //                print(dict)
//                //                self.loadUserInfo(access_token!, uid: uid!)
//            }
//            }) { (_, error) -> Void in
//
//                print(error)
//        }
        
        NetworkTools.sharedTools.requestJsonDict(.POST, urlString: urlString, parameters: parameters) { (result, error) -> () in
            if error != nil {
                    finished(error: error)
                return
            }
            //执行成功
            let account = UserAccount(dict: result!)
            self.loadUserInfo(account, finished: finished)
            
        }
    }
    
    //    private func loadUserInfo(access_token: String,uid: String) {
    private func loadUserInfo(account: UserAccount,finished: (error: NSError?) -> ()) {
        
        print("==========================")
        let urlString = "2/users/show.json"
        let parameters = ["access_token": account.access_token!,"uid": account.uid!]
        NetworkTools.sharedTools.requestJsonDict(.GET, urlString: urlString, parameters: parameters) { (result, error) -> () in
            if error != nil {
                finished(error: error)
                return
            }
            //请求用户信息
            account.avatar_large = result!["avatar_large"] as? String
            account.name = result!["name"] as? String
            account.saveAccount()
            
            //执行闭包
            finished(error: nil)
        }
        

////        print(parameters)
//        let AF = AFHTTPSessionManager()
//        AF.GET(urlString, parameters: parameters, success: { (_, result) -> Void in
////                        print(result)
//            if let dict = result as? [String: AnyObject] {
//                account.avatar_large = dict["avatar_large"] as? String
//                account.name = dict["name"] as? String
//                account.saveAccount()
//                finished(error: nil)
//            }
//            }) { (_, error) -> Void in
//
////                finished(error: error)
//                print(error)
//        }
    }
}
